package com.bumptech.glide.signature;

import com.bumptech.glide.load.Key;
import com.bumptech.glide.util.LogUtil;
import ohos.bundle.BundleInfo;
import ohos.rpc.RemoteException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.VisibleForTesting;
import ohos.app.Context;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public final class ApplicationVersionSignature {

  private static final String TAG = "ApplicationVersionSignature";
  private static final ConcurrentMap<String, Key> PACKAGE_NAME_TO_KEY = new ConcurrentHashMap<>();

  @NotNull
  public static Key obtain(@NotNull Context context) {
    String packageName = context.getBundleName();
    Key result = PACKAGE_NAME_TO_KEY.get(packageName);
    if (result == null) {
      Key toAdd = obtainVersionSignature(context);
      result = PACKAGE_NAME_TO_KEY.putIfAbsent(packageName, toAdd);
      // There wasn't a previous mapping, so toAdd is now the Key.
      if (result == null) {
        result = toAdd;
      }
    }

    return result;
  }

  @VisibleForTesting
  static void reset() {
    PACKAGE_NAME_TO_KEY.clear();
  }

  @NotNull
  private static Key obtainVersionSignature(@NotNull Context context) {
    BundleInfo bundleInfo = getPackageInfo(context);
    String versionCode = getVersionCode(bundleInfo);
    return new ObjectKey(versionCode);
  }


  private static String getVersionCode(@Nullable BundleInfo bundleInfo) {
    String versionCode;
    if (bundleInfo != null) {
      versionCode = String.valueOf(bundleInfo.getVersionCode());
    } else {
      versionCode = UUID.randomUUID().toString();
    }
    return versionCode;
  }

  private static BundleInfo getPackageInfo(@NotNull Context context) {
    try {
      return context.getBundleManager().getBundleInfo(context.getBundleName(), 0);
    } catch (RemoteException e) {
      LogUtil.error(TAG, "remoteException occurred when get bundle info");
      return null;
    }
  }

  private ApplicationVersionSignature() {
    // Empty for visibility.
  }
}
